package com.dff.easy_excel_demo.controller;

import com.alibaba.excel.EasyExcel;
import com.dff.easy_excel_demo.entity.Student;
import com.dff.easy_excel_demo.listener.ExcelListener;
import com.dff.easy_excel_demo.service.HandleExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * create by: Du.ff
 */
@Controller
@RequestMapping("excel")
public class TestController {

    @Autowired
    private HandleExcelService handleExcelService;

    @RequestMapping("index")
    public String index() {
        return "/index.html";
    }

    @RequestMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        List<Student> students = handleExcelService.list();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生列表", "UTF-8").replaceAll("\\+", "%20");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Student.class).sheet("模板").doWrite(students);
    }

    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Student.class, new ExcelListener(handleExcelService)).sheet().doRead();
        return "success";
    }

}
